package com.hxzy.service.impl;

import com.hxzy.dto.MenuSearchDTO;
import com.hxzy.entity.AdminUser;
import com.hxzy.entity.Menu;
import com.hxzy.mapper.MenuMapper;
import com.hxzy.service.MenuService;
import com.hxzy.vo.MenuTreeVO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 类说明
 *
 * @author admin
 * @date 2021-09-06
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class MenuServiceImpl extends CommonServiceImpl<Menu, Long> implements MenuService {

    private MenuMapper menuMapper;

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
        super.setMyBatisBaseDao(menuMapper);
    }

    @Override
    public List<Menu> selectAllMenu() {
        return this.menuMapper.selectAllMenu();
    }

    @Override
    public List<Long> selectRoleOwnMenuId(Integer roleId) {
        return this.menuMapper.selectRoleOwnMenuId(roleId);
    }

    @Override
    public List<Menu> selectAllMenuInfo(MenuSearchDTO menuSearchDTO) {
        return this.menuMapper.selectAllMenuInfo(menuSearchDTO);
    }

    /**
     *  当前用户拥有的菜单给首页菜单用
     * @param adminUserId
     * @return
     */
    @Override
    public List<MenuTreeVO> findCurrentUserOwnerMenu(Integer adminUserId) {
       //最终返回的自定义树型菜单
        List<MenuTreeVO>  menuTreeVOList  =new ArrayList<>();

        //数据库中当前用户拥有的菜单
        List<Menu> allList=this.menuMapper.findCurrentUserOwnerMenu(adminUserId);

        //组装根节点
        allList.stream().filter(p->p.getParentId().equals(0L)).forEach(p->{

            MenuTreeVO menuTreeVO=new MenuTreeVO();
            //工具反射复制对象
            BeanUtils.copyProperties(p,menuTreeVO);
             //加载下一级
            recursionChildrenMenu( allList,menuTreeVO );
            //添加到集合中
            menuTreeVOList.add(menuTreeVO);
        });

        return menuTreeVOList;
    }

    private void   recursionChildrenMenu(List<Menu> allList,MenuTreeVO parent){
       List<MenuTreeVO> childrenList=new ArrayList<>();

       //循环下级节点
        allList.stream().filter(p->p.getParentId().equals(parent.getId())).forEach(p-> {
            MenuTreeVO children=new MenuTreeVO();
            //工具反射复制对象
            BeanUtils.copyProperties(p,children);

            //递归下一级
            recursionChildrenMenu(allList, children);

            //添加到集合中
            childrenList.add(children);
        });

       if(childrenList.size()>0){
           parent.setChildren(childrenList);
       }
    }



}
